package main

import (
	"bufio"
	"fmt"
	"os"
	"os/exec"
	"strings"
	"syscall"

	"golang.org/x/term"
)

func checkAndAddHostsEntry(domain string) error {
	hostsFile := "/etc/hosts"
	hostEntry := fmt.Sprintf("127.0.0.1 %s", domain)
	
	// 检查hosts文件是否已有该条目
	file, err := os.Open(hostsFile)
	if err != nil {
		return fmt.Errorf("无法打开hosts文件: %v", err)
	}
	defer file.Close()
	
	scanner := bufio.NewScanner(file)
	for scanner.Scan() {
		line := strings.TrimSpace(scanner.Text())
		if line == hostEntry {
			fmt.Printf("hosts文件已存在条目: %s\n", hostEntry)
			return nil
		}
	}
	
	// 如果没有找到条目，需要添加
	fmt.Printf("需要添加hosts条目: %s\n", hostEntry)
	
	// 尝试直接写入
	if err := appendToHosts(hostsFile, hostEntry); err != nil {
		fmt.Println("权限不足，需要管理员权限...")
		return addHostsWithSudo(hostEntry)
	}
	
	return nil
}

func appendToHosts(hostsFile, entry string) error {
	file, err := os.OpenFile(hostsFile, os.O_APPEND|os.O_WRONLY, 0644)
	if err != nil {
		return err
	}
	defer file.Close()
	
	_, err = file.WriteString(fmt.Sprintf("\n%s\n", entry))
	return err
}

func addHostsWithSudo(entry string) error {
	fmt.Print("请输入管理员密码: ")
	password, err := term.ReadPassword(int(syscall.Stdin))
	if err != nil {
		return fmt.Errorf("读取密码失败: %v", err)
	}
	fmt.Println()
	
	cmd := exec.Command("sudo", "-S", "sh", "-c", fmt.Sprintf("echo '%s' >> /etc/hosts", entry))
	cmd.Stdin = strings.NewReader(string(password) + "\n")
	
	if err := cmd.Run(); err != nil {
		return fmt.Errorf("添加hosts条目失败: %v", err)
	}
	
	fmt.Printf("成功添加hosts条目: %s\n", entry)
	return nil
}